//
//  EmoticonCell.swift
//  VVbo
//
//  Created by Mr.Run on 2017/9/11.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit

@objc protocol EmoticonCellDelegate:NSObjectProtocol{
    func emoticonCellDidSelectedEmoticon(cell:EmoticonCell, em:Emoticon?)
}

class EmoticonCell: UICollectionViewCell {
    
    weak var delegate:EmoticonCellDelegate?
    
    @IBOutlet weak var label: UILabel!
//    override func awakeFromNib() {
//        super.awakeFromNib()
//        setupUI()
//    }
    
    fileprivate lazy var tipView = EmoticonTipView()
    
    var emoticons:[Emoticon]? {
        didSet{
            print(emoticons?.count ?? "")
            
            for v in contentView.subviews {
                v.isHidden = true
            }
            contentView.subviews.last?.isHidden = false
            
            for (i, em) in (emoticons ?? []).enumerated() {
                if let btn = contentView.subviews[i] as? UIButton {
                    btn.setImage(em.image, for: [])
                    
                    btn.setTitle(em.emoji, for: [])
                    
                    btn.isHidden = false
                }
                
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        
        guard let w = newWindow else {
            return
        }
        
        w.addSubview(tipView)
        tipView.isHidden = true
        
        
        
    }
    
    @objc fileprivate func selectedEmoticonBtn(btn: UIButton) {
        let tag = btn.tag
        var em: Emoticon?
        if tag<(emoticons?.count)! {
            em = emoticons?[tag]
        }
//        print(em ?? "")
        
        delegate?.emoticonCellDidSelectedEmoticon(cell: self, em: em)
        
    }
    
    @objc fileprivate func longGesture(gesture: UILongPressGestureRecognizer) {
        
        let location = gesture.location(in: self)
        guard let btn = buttonWithLocation(location: location) else {
            tipView.isHidden = true
            return
        }
        
        switch gesture.state {
        case .began, .changed:
            tipView.isHidden = false
            
            let center = self.convert(btn.center, to: window)
            
            tipView.center = center
            
            if btn.tag < (emoticons?.count)! {
                tipView.emoticon = emoticons?[btn.tag]
            }
        case .ended:
            tipView.isHidden = true
            selectedEmoticonBtn(btn: btn)
        case .failed, .cancelled:
            tipView.isHidden = true
        default:
            break
        }
        
    }
    
    fileprivate func buttonWithLocation(location: CGPoint) -> UIButton? {
        
        for btn in contentView.subviews as! [UIButton] {
            
            if btn.frame.contains(location) && !btn.isHidden && btn != contentView.subviews.last {
                return btn
            }
        }
        return nil
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

fileprivate extension EmoticonCell {
    
    func setupUI() {
        
        let rowCount = 3
        let colCount = 7
        
        let leftMargin:CGFloat = 8
        let bottomMargin:CGFloat = 16
        
        let w = (bounds.width - leftMargin*2)/CGFloat(colCount)
        let h = (bounds.height - bottomMargin)/CGFloat(rowCount)
        
        
        for i in 0..<21 {
            let btn = UIButton()
            
            let row = i / colCount
            let col = i % colCount
            
            let x = leftMargin + CGFloat(col)*w
            let y = CGFloat(row)*h
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            contentView.addSubview(btn)
            btn.tag = i
//            btn.addTarget(self, action: #selector(selectedEmoticonBtn), for: .touchUpInside)
            btn.addTarget(self, action: #selector(selectedEmoticonBtn), for: .touchUpInside)
            
        }
        let removeBtn = contentView.subviews.last as! UIButton
        let image = UIImage(named: "compose_emotion_delete_highlighted", in: EmoticonManager.shared.bundle, compatibleWith: nil)
        removeBtn.setImage(image, for: [])
        
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture))
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
    }
    
}

